import React, { Component } from 'react'
import { Row, Col, Form, Input, Modal, Select, TreeSelect } from 'antd'
import { connect } from 'dva'
import styles from './Index.less'
import { findUserByOrgId } from './services/approve'
import settings from '@/../config/defaultSettings'

const FormItem = Form.Item
const { Option } = Select
const { TextArea } = Input

@connect(({ loading, approve, department }) => ({
  department,
  approve,
  loading: loading.models.approve,
}))
@Form.create()
export default class AOEForm extends Component {
  state = {
    approverData: [],
    //
    treeSelectDisabled: false,
  }

  async componentDidMount() {
    const { dispatch } = this.props
    await dispatch({
      type: 'department/listAll',
    })
    this.setState({
      approverData: this.props.department.allDepData,
      treeSelectDisabled: this.props.approve.currentItem.type === 4,
    })
  }

  // 组件改为rerender 而不是控制显隐
  // async componentDidUpdate(prevProps) {
  //   const { form } = this.props

  //   if (this.props.showModal && !prevProps.showModal) {
  //     form.resetFields()
  //   }
  // }

  handleSelectChange = value => {
    const { type } = this.props.approve.currentItem
    this.setState({
      treeSelectDisabled: type !== 4 ? value === '0000' : true,
    })
  }

  // 关闭窗口
  handleClose = () => {
    this.props.modalCloseCallback()
  }

  // 弹窗确认
  handleConfirm = () => {
    //
    const { form } = this.props
    const { currentItem } = this.props.approve
    // 表单验证
    form.validateFields((err, fieldsValue) => {
      if (err) return

      const values = {
        ...fieldsValue,
        id: currentItem.id,
      }

      if (values.status === '0000') {
        delete values.approveBy
      }

      this.props.modalConfirmCallback(values)
    })
  }

  genTreeNode = (parentId, data) => ({
    id: data.id,
    // pId: parentId,
    value: data.id,
    name: data.realityName,
    isEnd: true,
    isLeaf: true,
    status: '0001',
  })

  // treeSelect 异步加载
  onLoadData = treeNode =>
    new Promise(async (resolve, reject) => {
      if (treeNode.props.shouldLoad) {
        const orgId = treeNode.props.id
        // 加载人员
        const { step } = this.props.approve.currentItem
        try {
          const res = await findUserByOrgId({ id: orgId, type: step })
          if (res && res.success) {
            this.setState(oldState => {
              const org = this.findTreeNodeData(orgId, oldState.approverData)
              const childrenNodes = res.data.map(item => this.genTreeNode(orgId, item))
              org.children = childrenNodes

              resolve()
              return {
                approverData: oldState.approverData,
              }
            })
          }
        } catch (err) {
          console.log(err)
          reject(err)
        }
      } else {
        resolve()
      }
    })

  findTreeNodeData(id, data) {
    // eslint-disable-next-line no-restricted-syntax
    for (const item of data) {
      if (item.id === id) {
        return item
      }
      if (item.children) {
        const getOne = this.findTreeNodeData(id, item.children)
        if (getOne) return getOne
      }
    }
  }

  renderTreeData(data) {
    return data
      .map(item => {
        if (item.status === '0001') {
          if (item.children) {
            return {
              title: item.name,
              key: item.id,
              value: item.id,
              id: item.id,
              children: this.renderTreeData(item.children),
              disabled: true,
            }
          }
          return {
            title: item.name,
            key: item.id,
            value: item.id,
            id: item.id,
            isLeaf: item.isEnd || false,
            shouldLoad: !item.isEnd,
            disabled: !item.isEnd,
          }
        }
        return null
      })
      .filter(item => item || false)
  }

  // 渲染界面
  render() {
    const { loading, showModal } = this.props
    const { getFieldDecorator, getFieldsValue } = this.props.form
    const depData = this.state.approverData
    const treeData = this.renderTreeData(depData)
    const { step } = this.props.approve.currentItem
    const { treeSelectDisabled } = this.state

    const formRowOne = {
      labelCol: { span: 4 },
      wrapperCol: { span: 10 },
    }
    const formRowTwo = {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    }
    return (
      <Modal
        maskClosable={false}
        confirmLoading={loading}
        cancelText="取消"
        okText="确认提交"
        onCancel={() => this.handleClose()}
        visible={showModal}
        width={660}
        onOk={() => this.handleConfirm()}
        title="审批"
      >
        <Form className={styles.modalForm} onSubmit={this.handleSearch}>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={24} sm={24}>
              <FormItem label="审批意见" {...formRowOne}>
                {getFieldDecorator('status', {
                  initialValue: '0002',
                  rules: [{ required: true, message: '不能为空' }],
                })(
                  <Select onChange={this.handleSelectChange}>
                    <Option key="0002" value="0002">
                      同意
                    </Option>
                    <Option key="0000" value="0000">
                      拒绝
                    </Option>
                  </Select>,
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={24} sm={24}>
              <FormItem label="原因" {...formRowTwo}>
                {getFieldDecorator('remark', {
                  rules: [
                    { required: getFieldsValue().status === '0000', message: '拒绝时不能为空' },
                  ],
                })(<TextArea placeholder="请输入" maxLength={settings.inputMaxLength} />)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={24} sm={24}>
              <FormItem label={step === '2' ? '执行人' : '下级审批人'} {...formRowOne}>
                {getFieldDecorator('approveBy')(
                  <TreeSelect
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    showCheckedStrategy={TreeSelect.SHOW_ALL}
                    allowClear
                    treeNodeFilterProp="title"
                    placeholder="请选择人员"
                    loadData={this.onLoadData}
                    treeData={treeData}
                    disabled={treeSelectDisabled}
                  ></TreeSelect>,
                )}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    )
  }
}
